package com.good.child.widgets.addressPicker;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;

import androidx.lifecycle.MutableLiveData;

import com.good.child.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Create on: 2024/2/28
 * by Mr.Zhu
 * Description: TODO
 */
public class AddressPicker implements DialogInterface.OnDismissListener {

    private List<AddressBean> addressBeans;
    private MutableLiveData<Boolean> dataChangeListener = new MutableLiveData<>();
    private AreaPickerView areaPickerView;

    @Override
    public void onDismiss(DialogInterface dialog) {
        dismiss();
    }

    static class Holder {
        private static AddressPicker INSTANCE = new AddressPicker();
    }

    private AddressPicker() {

    }

    public static AddressPicker get() {
        return Holder.INSTANCE;
    }


    public synchronized boolean isLoad() {
        return addressBeans != null && addressBeans.size() > 0;
    }

    /**
     * 初始化地址数据，建议在app启动时并且在非UI线程调用，
     *
     * @param addressBeans
     */
    public synchronized void init(List<AddressBean> addressBeans) {
        if (this.dataChangeListener == null) {
            this.dataChangeListener = new MutableLiveData<>();
        }
        this.addressBeans = addressBeans;
        dataChangeListener.postValue(true);
    }

    public List<AddressBean> getAddressBeans() {
        return addressBeans;
    }

    public MutableLiveData<Boolean> getDataChangeListener() {
        return dataChangeListener;
    }


    /**
     * 根据id 查询数据
     *
     * @param province
     * @param city
     * @param area
     * @return
     */
    public List<AddressBean> queryByName(String province, String city, String area) {
        if (addressBeans == null)
            return null;
        AddressBean provinceBean = findByName(addressBeans, province);
        if (provinceBean == null) {
            return null;
        }
        List<AddressBean> temp = new ArrayList<>();
        temp.add(provinceBean);
        AddressBean cityBean = findByName(provinceBean.getChildren(), city);
        if (cityBean == null) {
            temp.add(null);
            temp.add(null);
            return temp;
        }
        temp.add(cityBean);
        AddressBean areaBean = findByName(cityBean.getChildren(), area);
        temp.add(areaBean);
        return temp;
    }

    /**
     * 根据id 查询数据
     *
     * @param provinceId
     * @param cityId
     * @param areaId
     * @return
     */
    public List<AddressBean> queryById(String provinceId, String cityId, String areaId) {
        if (addressBeans == null)
            return null;
        AddressBean provinceBean = findById(addressBeans, provinceId);
        if (provinceBean == null) {
            return null;
        }
        List<AddressBean> temp = new ArrayList<>();
        temp.add(provinceBean);
        AddressBean cityBean = findById(provinceBean.getChildren(), cityId);
        if (cityBean == null) {
            temp.add(null);
            temp.add(null);
            return temp;
        }
        temp.add(cityBean);
        AddressBean areaBean = findById(cityBean.getChildren(), areaId);
        temp.add(areaBean);
        return temp;
    }

    private AddressBean findByName(List<AddressBean> list, String name) {
        if (list == null)
            return null;
        final int size = list.size();
        for (int i = 0; i < size; i++) {
            AddressBean addressBean = list.get(i);
            if (name != null && name.contains(addressBean.getAreaName())) {
                return addressBean;
            }
        }
        return null;
    }

    private AddressBean findById(List<AddressBean> list, String id) {
        if (list == null)
            return null;
        final int size = list.size();
        for (int i = 0; i < size; i++) {
            AddressBean addressBean = list.get(i);
            if (addressBean.getId().equals(id)) {
                return addressBean;
            }
        }
        return null;
    }

    /**
     * 显示地址选择器
     *
     * @param activity
     * @param callback
     */
    public void show(Activity activity, AreaPickerView.AreaPickerViewCallback callback) {
        show(activity, callback, Config.Builder.create(activity.getApplicationContext()).build());
    }

    /**
     * 新的显示地址选择器
     * 省市不允许修改
     * @param activity
     * @param callback
     */
    public void show(Activity activity, AreaPickerView.AreaPickerViewCallback callback,String province,String city) {
        show(activity, callback, Config.Builder.create(activity.getApplicationContext()).withSelecteds(province,city,"").build());
    }

    /**
     * 显示地址选择器
     *
     * @param activity
     * @param callback
     */
    public void show(Activity activity, AreaPickerView.AreaPickerViewCallback callback, String... selecteds) {
        show(activity, callback, Config.Builder.create(activity.getApplicationContext()).withSelecteds(selecteds).build());
    }

    /**
     * 显示地址选择器
     *
     * @param activity
     * @param callback
     * @param config   配置信息
     */
    public void show(Activity activity, final AreaPickerView.AreaPickerViewCallback callback, final Config config) {
//        if (!isLoad()) {
//            Toast.makeText(activity, "地址数据加载中，请稍后", Toast.LENGTH_SHORT).show();
//            return;
//        }
        areaPickerView = new AreaPickerView(activity, R.style.Dialog, deepCopyList(this.addressBeans, config));
        areaPickerView.setAreaPickerViewCallback(new AreaPickerView.AreaPickerViewCallback() {
            @Override
            public void callback(AddressBean province, AddressBean city, AddressBean area) {
                if (province == null || city == null)
                    return;
                if (config.showArea && area == null)
                    return;
                callback.callback(province, city, area);
            }
        });
        areaPickerView.setHeight(config.height);
        areaPickerView.setOnDismissListener(this);
        areaPickerView.show();
        areaPickerView.setSelect(config.selecteds);
    }

    @SuppressWarnings("unchecked")
    public static List<AddressBean> deepCopyList(List<AddressBean> src, Config config) {
        List<AddressBean> temp = new ArrayList<>();
        if (src == null)
            src = new ArrayList<>();
        final int size = src.size();
        for (int i = 0; i < size; i++) {
            AddressBean addressBean = src.get(i);
            if (config.province != null) {
                if (addressBean.getAreaName().equals(config.province)) {
                    temp.add(new AddressBean(null, src.get(i), config.showArea, config.city));
                    break;
                }
            } else {
                temp.add(new AddressBean(null, src.get(i), config.showArea, config.city));
            }
        }
        return temp;
    }


    /**
     * 关闭地址选择
     */
    public void dismiss() {
        if (areaPickerView != null && areaPickerView.isShowing()) {
            areaPickerView.dismiss();
        }
        areaPickerView = null;
    }

    public static class Config {
        private int height;
        private boolean showArea;
        //显示指定省份指定城市
        private String province;
        private String city;
        private String[] selecteds;

        public static final class Builder {
            private int height;
            private String[] selecteds;
            private boolean showArea = true;
            private String province;
            private String city;
            private static int screenHeight;

            private Builder(Context context) {
                if (screenHeight == 0) {
                    screenHeight = context.getResources().getDisplayMetrics().heightPixels;
                }
            }

            public static Builder create(Context context) {
                return new Builder(context);
            }

            public Builder withHeight(int height) {
                this.height = height;
                return this;
            }

            public Builder withShowArea(boolean showArea) {
                this.showArea = showArea;
                return this;
            }

            public Builder withProvince(String province) {
                this.province = province;
                return this;
            }

            public Builder withCity(String city) {
                this.city = city;
                return this;
            }

            public Builder withSelecteds(String... selecteds) {
                this.selecteds = selecteds;
                return this;
            }

            public Config build() {
                Config config = new Config();
                config.selecteds = this.selecteds;
                if (this.height == 0) {
                    this.height = screenHeight / 2;
                }
                config.height = this.height;
                config.showArea = this.showArea;
                config.province = this.province;
                config.city = this.city;
                return config;
            }
        }
    }


    public interface InitCallback {
        List<AddressBean> init();
    }
}
